<script lang="tsx" setup>
import type { FileInfo as FileItem, ShareItem } from '#/api/openapi';

import { computed, onMounted, ref } from 'vue';

import { usePreferences } from '@vben/preferences';

import {
  Delete,
  Download,
  History,
  PreviewOpen,
  Recycling as Recycle,
  Delete as RecycleBin,
} from '@icon-park/vue-next';

import { FilePreviewAdvanced } from '#/components/FilePreview';
import Button from '#/components/fluentui/Button.vue';
import Dialog from '#/components/fluentui/Dialog.vue';
import DialogBody from '#/components/fluentui/DialogBody.vue';
import Dropdown from '#/components/fluentui/Dropdown.vue';
import ListBox from '#/components/fluentui/ListBox.vue';
import Option from '#/components/fluentui/Option.vue';
import TextInput from '#/components/fluentui/TextInput.vue';
import { confirm } from '#/components/global-dialog';
import {
  ShareCodeInputDialog,
  ShareInfoDialog,
} from '#/components/ShareDialog';
import { useFilesStore, useShareHistoryStore } from '#/store';
import { downloadFile } from '#/utils/download';
import { getFileCategory, getFileIcon } from '#/utils/icon';
import { formatTime } from '#/utils/time';

const { isDark } = usePreferences();
const shareHistoryStore = useShareHistoryStore();
const filesStore = useFilesStore();

const searchQuery = ref('');
const selectedCategory = ref('all');
const sortBy = ref('date');
const currentPage = ref(1);
const pageSize = 10;
const previewFileData = ref<FileItem>();
const showPreviewDialog = ref(false);

// 分享码相关状态
const showShareCodeDialog = ref(false);
const showShareInfoDialog = ref(false);
const showShareHistoryDialog = ref(false); // 新增：分享历史弹窗状态
const shareInfo = ref<ShareItem>();

// 初始化示例数据
onMounted(() => {
  filesStore.initSampleData();
});

// 使用 store 中的文件数据，并应用筛选和排序
const filteredFiles = computed(() => {
  let result = filesStore.getAllFiles;

  // 搜索筛选
  if (searchQuery.value) {
    result = result.filter((file) =>
      file.fileName?.toLowerCase().includes(searchQuery.value.toLowerCase()),
    );
  }

  // 分类筛选 - 根据文件扩展名确定分类
  if (selectedCategory.value && selectedCategory.value !== 'all') {
    result = result.filter((file) => {
      const ext = file.fileName?.split('.').pop()?.toLowerCase();
      const category = getFileCategory(ext || '');
      return category === selectedCategory.value;
    });
  }

  // 排序
  result.sort((a, b) => {
    switch (sortBy.value) {
      case 'date': {
        return (
          new Date(b.uploadTime || '').getTime() -
          new Date(a.uploadTime || '').getTime()
        );
      }
      case 'size': {
        return (b.fileSize || 0) - (a.fileSize || 0);
      }
      default: {
        return (a.fileName || '').localeCompare(b.fileName || '');
      }
    }
  });

  // 分页
  const start = (currentPage.value - 1) * pageSize;
  const end = start + pageSize;
  return result.slice(start, end);
});

const totalFiles = computed(() => {
  let result = filesStore.getAllFiles;

  if (searchQuery.value) {
    result = result.filter((file) =>
      file.fileName?.toLowerCase().includes(searchQuery.value.toLowerCase()),
    );
  }

  if (selectedCategory.value && selectedCategory.value !== 'all') {
    result = result.filter((file) => {
      const ext = file.fileName?.split('.').pop()?.toLowerCase();
      const category = getFileCategory(ext || '');
      return category === selectedCategory.value;
    });
  }

  return result.length;
});

const totalPages = computed(() => Math.ceil(totalFiles.value / pageSize));

// 分页函数
const previousPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
  }
};

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
  }
};

// 预览文件
const showPreview = (file: FileItem) => {
  previewFileData.value = file;
  showPreviewDialog.value = true;
};

const closePreview = () => {
  previewFileData.value = undefined;
  showPreviewDialog.value = false;
};

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes';

  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));

  return `${Number.parseFloat((bytes / k ** i).toFixed(2))} ${sizes[i]}`;
};

// 分享码相关功能
const openShareCodeDialog = () => {
  showShareCodeDialog.value = true;
};

const handleShareFound = (shareData: ShareItem) => {
  shareInfo.value = shareData;
  console.log('分享信息:', shareData);

  // 保存到分享历史记录
  if (shareData.code) {
    shareHistoryStore.addShareHistory(shareData.code, shareData);
  }

  showShareInfoDialog.value = true;
};

const handleShareError = (errorMessage: string) => {
  console.error('分享码错误:', errorMessage);
};

const handleDownloadFile = (code: string, file: FileItem) => {
  downloadFile(code, file);

  // 如果有当前的分享信息，记录下载
  if (shareInfo.value?.code) {
    shareHistoryStore.recordDownload(shareInfo.value.code, file.id);
  }
};

// 文件预览组件的下载处理函数 (只接收文件参数)
const handlePreviewDownload = (file: FileItem) => {
  if (shareInfo.value?.code) {
    handleDownloadFile(shareInfo.value.code, file);
  }
};

const handleDownloadFiles = (code: string, files: FileItem[]) => {
  console.log('批量下载文件:', files);
  files.forEach((file) => {
    downloadFile(code, file);
    // 记录每个文件的下载
    if (shareInfo.value?.code) {
      shareHistoryStore.recordDownload(shareInfo.value.code, file.id);
    }
  });
};

// 分享历史相关功能
const openShareHistoryDialog = () => {
  showShareHistoryDialog.value = true;
};

const selectHistoryShare = (historyItem: any) => {
  shareInfo.value = historyItem.shareItem;
  showShareHistoryDialog.value = false;
  showShareInfoDialog.value = true;
};

const removeHistoryItem = async (id: string) => {
  if (await confirm('确认删除此取件记录吗？此操作无法撤销。'))
    shareHistoryStore.removeShareHistory(id);
};

const clearAllHistory = async () => {
  if (await confirm('确认清空所有取件记录吗？此操作无法撤销。'))
    shareHistoryStore.clearHistory();
};

// 删除文件功能
const removeFile = async (file: FileItem) => {
  if (
    file.id &&
    (await confirm(`确认删除文件 "${file.fileName}" 吗？此操作无法撤销。`))
  ) {
    filesStore.removeFile(file.id);
  }
};
</script>

<template>
  <div
    class="bg-background text-foreground mx-auto min-h-screen max-w-7xl px-6 py-8"
    :data-theme="isDark ? 'dark' : 'light'"
  >
    <!-- 页面标题 -->
    <div class="mb-8 text-center">
      <h1 class="mb-3 text-4xl font-bold">文件下载</h1>
      <p class="text-lg text-gray-600 dark:text-gray-300">
        浏览和下载可用的文件
      </p>

      <!-- 下载统计信息 -->
      <div
        class="mt-4 flex justify-center gap-6 text-sm text-gray-600 dark:text-gray-300"
      >
        <div class="flex items-center gap-1">
          <span>总文件:</span>
          <span class="font-semibold text-blue-600">{{
            filesStore.getDownloadStats.totalFiles
          }}</span>
        </div>
        <div class="flex items-center gap-1">
          <span>已下载:</span>
          <span class="font-semibold text-green-600">{{
            filesStore.getDownloadStats.downloadedFiles
          }}</span>
        </div>
        <div class="flex items-center gap-1">
          <span>总下载次数:</span>
          <span class="font-semibold text-purple-600">{{
            filesStore.getDownloadStats.totalDownloads
          }}</span>
        </div>
      </div>

      <!-- 添加分享码按钮 -->
      <div class="mt-4 flex justify-center gap-3">
        <Button @click="openShareCodeDialog" appearance="primary" size="large">
          <template #start>
            <Recycle />
          </template>
          使用分享码
        </Button>
        <Button
          @click="openShareHistoryDialog"
          appearance="outline"
          size="large"
        >
          <template #start>
            <History />
          </template>
          取件记录
        </Button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div
      class="mb-6 flex flex-col gap-4 md:flex-row md:items-center md:justify-between"
    >
      <!-- 搜索框 -->
      <div class="relative max-w-md flex-1">
        <TextInput v-model="searchQuery" placeholder="搜索文件..." />
      </div>

      <!-- 筛选器 -->
      <div class="flex gap-3">
        <Dropdown v-model="selectedCategory">
          <ListBox>
            <Option value="all">所有类型</Option>
            <Option value="image">图片</Option>
            <Option value="document">文档</Option>
            <Option value="video">视频</Option>
            <Option value="archive">压缩包</Option>
          </ListBox>
        </Dropdown>

        <Dropdown v-model="sortBy">
          <ListBox>
            <Option value="name"> 按名称排序 </Option>
            <Option value="size">按大小排序</Option>
            <Option value="date">按日期排序</Option>
          </ListBox>
        </Dropdown>
      </div>
    </div>

    <!-- 文件列表 -->
    <div class="mb-8 grid grid-cols-1 gap-4 lg:grid-cols-2 xl:grid-cols-3">
      <div
        v-for="file in filteredFiles"
        :key="file.id"
        class="relative rounded-lg border border-gray-200 bg-white p-4 transition-colors hover:bg-gray-50 dark:border-gray-700 dark:bg-gray-800 dark:hover:bg-gray-700"
      >
        <!-- 删除按钮 - 右上角 -->
        <Button
          icon-only
          @click="removeFile(file)"
          class="absolute right-2 top-2 flex h-8 w-8 items-center justify-center rounded-full bg-red-100 text-red-600 opacity-70 transition-all hover:bg-red-200 hover:opacity-100 dark:bg-red-900/30 dark:text-red-400 dark:hover:bg-red-900/50"
          title="删除文件"
        >
          <RecycleBin size="16" />
        </Button>

        <!-- 文件信息部分 -->
        <div class="mb-3 flex items-start space-x-3 pr-8">
          <component
            :is="getFileIcon(file.fileName)"
            class="h-6 w-6 flex-shrink-0 text-blue-600"
          />
          <div class="min-w-0 flex-1">
            <h3 class="truncate text-sm font-medium" :title="file.fileName">
              {{ file.fileName }}
            </h3>
            <p class="text-xs text-gray-500 dark:text-gray-400">
              {{ formatFileSize(file.fileSize || 0) }} · {{ file.uploadTime }}
            </p>
            <div class="mt-1 flex flex-wrap items-center gap-1">
              <span
                class="inline-flex items-center rounded-full bg-blue-100 px-2 py-0.5 text-xs font-medium text-blue-800 dark:bg-blue-900 dark:text-blue-200"
              >
                {{
                  getFileCategory(
                    file.fileName?.split('.').pop()?.toLowerCase() || '',
                  )
                }}
              </span>
              <!-- 最近下载指示器 -->
              <span
                v-if="
                  file.lastDownloadTime &&
                  Date.now() - file.lastDownloadTime < 24 * 60 * 60 * 1000
                "
                class="inline-flex items-center rounded-full bg-green-100 px-2 py-0.5 text-xs font-medium text-green-800 dark:bg-green-900 dark:text-green-200"
              >
                最近下载
              </span>
            </div>
          </div>
        </div>

        <!-- 下载统计 -->
        <div
          class="mt-3 flex items-center justify-between text-xs text-gray-500 dark:text-gray-400"
        >
          <div class="flex gap-2">
            <span>总下载: {{ file.downloadCount || 0 }} 次</span>
            <span v-if="file.localDownloadCount">
              本地: {{ file.localDownloadCount }} 次
            </span>
          </div>
          <div class="flex flex-col items-end">
            <span>{{ formatTime(file.uploadTime) }}</span>
            <span v-if="file.lastDownloadTime" class="text-green-600">
              最后下载: {{ formatTime(new Date(file.lastDownloadTime)) }}
            </span>
          </div>
        </div>

        <!-- 操作按钮部分 -->
        <div class="mt-3 flex gap-2">
          <Button @click="showPreview(file)" appearance="subtle" class="flex-1">
            <template #start>
              <PreviewOpen />
            </template>
            预览
          </Button>
          <Button
            @click="downloadFile(file.code, file)"
            appearance="subtle"
            class="flex-1"
          >
            <template #start>
              <Download />
            </template>
            下载
          </Button>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="flex items-center justify-between">
      <div class="text-sm text-gray-500 dark:text-gray-400">
        显示 {{ Math.min((currentPage - 1) * pageSize + 1, totalFiles) }} -
        {{ Math.min(currentPage * pageSize, totalFiles) }}
        共 {{ totalFiles }} 个文件
      </div>
      <div class="flex space-x-2">
        <Button
          @click="previousPage"
          :disabled="currentPage === 1"
          appearance="outline"
          size="small"
        >
          上一页
        </Button>
        <span
          class="flex items-center px-3 py-1 text-sm text-gray-500 dark:text-gray-400"
        >
          {{ currentPage }} / {{ totalPages }}
        </span>
        <Button
          @click="nextPage"
          :disabled="currentPage === totalPages"
          appearance="outline"
          size="small"
        >
          下一页
        </Button>
      </div>
    </div>

    <!-- 高级文件预览组件 - 支持图片、PDF、视频、音频和文本预览 -->
    <FilePreviewAdvanced
      v-model:visible="showPreviewDialog"
      :file-data="previewFileData"
      :share-code="shareInfo?.code || ''"
      :enable-advanced-preview="true"
      @close="closePreview"
      @download="handlePreviewDownload"
    />

    <!-- 分享码输入弹窗 -->
    <ShareCodeInputDialog
      v-model="showShareCodeDialog"
      @share-found="handleShareFound"
      @error="handleShareError"
    />

    <!-- 分享信息展示弹窗 -->
    <ShareInfoDialog
      v-model="showShareInfoDialog"
      :share-info="shareInfo"
      @download-file="handleDownloadFile"
      @download-all="handleDownloadFiles"
    />

    <!-- 分享历史记录弹窗 -->
    <Dialog
      v-model="showShareHistoryDialog"
      type="modal"
      aria-labelledby="share-history-dialog-title"
    >
      <DialogBody>
        <div class="mx-auto w-full max-w-2xl">
          <!-- 标题 -->
          <div class="mb-6 flex items-center justify-between">
            <h2
              id="share-history-dialog-title"
              class="text-2xl font-bold text-gray-900 dark:text-gray-100"
            >
              取件历史记录
            </h2>
            <Button
              appearance="subtle"
              size="small"
              @click="clearAllHistory"
              v-if="shareHistoryStore.getAllHistory.length > 0"
              class="ml-2 text-red-500"
            >
              <template #start>
                <Delete />
              </template>
              清空全部
            </Button>
          </div>

          <!-- 历史记录列表 -->
          <div
            v-if="shareHistoryStore.getAllHistory.length === 0"
            class="py-8 text-center"
          >
            <div class="mb-4 text-gray-500 dark:text-gray-400">
              <div class="mb-2 flex w-full justify-center">
                <History size="38" class="size-large" />
              </div>
              <p>暂无分享历史记录</p>
              <p class="text-sm">使用分享码后会自动保存到这里</p>
            </div>
          </div>

          <div v-else class="max-h-96 space-y-3 overflow-y-auto">
            <div
              v-for="item in shareHistoryStore.getAllHistory"
              :key="item.id"
              class="cursor-pointer rounded-lg border border-gray-200 bg-white p-4 transition-colors hover:bg-gray-50 dark:border-gray-700 dark:bg-gray-800 dark:hover:bg-gray-700"
              @click="selectHistoryShare(item)"
            >
              <div class="flex items-start justify-between">
                <div class="min-w-0 flex-1">
                  <div class="mb-2 flex items-center gap-2">
                    <span
                      class="inline-flex items-center rounded-full bg-blue-100 px-2.5 py-0.5 text-xs font-medium text-blue-800 dark:bg-blue-900 dark:text-blue-200"
                    >
                      {{ item.shareCode }}
                    </span>
                    <span class="text-xs text-gray-500 dark:text-gray-400">
                      {{ item.formattedTime }}
                    </span>
                  </div>

                  <div class="mb-2 text-sm text-gray-600 dark:text-gray-300">
                    {{ item.shareItem.files?.length || 0 }} 个文件
                    <span v-if="item.downloadCount" class="ml-2">
                      · 已下载 {{ item.downloadCount }} 次
                    </span>
                  </div>

                  <!-- 文件列表预览 -->
                  <div class="text-xs text-gray-500 dark:text-gray-400">
                    <span
                      v-for="(file, index) in (
                        item.shareItem.files || []
                      ).slice(0, 3)"
                      :key="file.id"
                    >
                      {{ file.fileName
                      }}{{
                        index <
                        Math.min(2, (item.shareItem.files?.length || 0) - 1)
                          ? ', '
                          : ''
                      }}
                    </span>
                    <span v-if="(item.shareItem.files?.length || 0) > 3">
                      等 {{ item.shareItem.files?.length }} 个文件
                    </span>
                  </div>

                  <!-- 消息预览 -->
                  <div
                    v-if="
                      item.shareItem.messages &&
                      item.shareItem.messages.length > 0 &&
                      item.shareItem.messages[0]?.content
                    "
                    class="mt-1 text-xs italic text-gray-600 dark:text-gray-300"
                  >
                    "{{ item.shareItem.messages[0].content }}"
                  </div>
                </div>

                <Button
                  appearance="subtle"
                  size="small"
                  @click.stop="removeHistoryItem(item.id)"
                  class="ml-2 text-red-500"
                >
                  <template #start>
                    <Delete />
                  </template>
                  删除
                </Button>
              </div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="mt-6 flex justify-end">
            <Button appearance="subtle" @click="showShareHistoryDialog = false">
              关闭
            </Button>
          </div>
        </div>
      </DialogBody>
    </Dialog>
  </div>
</template>
